package main

import "fmt"
import "flag"
import "demoutil"
import "os"
import "strconv"
import "bufio"

//import "math/rand"

// Distributed System
import "shardkv"

//go run demo_server_kv.go

var DoTcp = flag.Bool("tcp", false, "communicate across tcp")
var DoAuto = flag.Bool("auto", true, "load hardcoded settings")
var Set_pid = flag.Int("pid", -1, "pid of shardmaster")

var ck *shardkv.Clerk

func main() {
	Init()
	err_msg := ""
	run := true
	execute := true
	cmd := demoutil.Make_cmd()
	line := ""
	in := bufio.NewReader(os.Stdin)
	var err error
	for run {
		fmt.Printf(">>>")
		// read space-seperated cmd into several arguments
		//fmt.Scanln(&line)
		line, err = in.ReadString('\n')
		if err != nil {
			panic(err)
		} else {
			execute = cmd.ParseInput(line)
			run = cmd.GetStatus()
			//line = ""
			if execute {
				err_msg = Execute(cmd.GetTodo())
				if err_msg != "" {
					fmt.Println("Error:" + err_msg)
				}
			}
		}
	}
}
func Init() {
	os.RemoveAll("/var/tmp/824-" + strconv.Itoa(os.Getpid()))
	fmt.Println("Welcome, Client :) ")
	flag.Parse()
	if *DoTcp {
		fmt.Println("connect with 'tcp'")
	} else {
		fmt.Println("Default: Connect with 'unix' instead of 'tcp'")
	}
	var smh []string
	if *DoAuto {
		smh = make([]string, 3)
		if *Set_pid == -1 {
			panic("need to set the pid of shardmaster: -pid=x")
		} else {

			for i := 0; i < 3; i++ {
				smh[i] = "/var/tmp/824-" + strconv.Itoa(*Set_pid) + "/px-20331-demo_sm-" + strconv.Itoa(i)
			}
		}
		ck = shardkv.MakeClerk(smh)
		fmt.Printf("Default: Connect to Shardmasters %v \n", smh)

	} else {
		panic("Haven't implement interactive manual input yet")
	}

}
func Execute(cc []string) string {
	err_msg := ""
	switch cc[0] {
	case "put":
		if len(cc) != 3 {
			err_msg = "put: need two arguments, " + strconv.Itoa(len(cc)-1) + " provided"
		} else {
			ck.Put(cc[1], cc[2])
			//go ck.Put(cc[1],cc[2])
		}
	case "get":
		if len(cc) != 2 {
			err_msg = "get: need one argument, " + strconv.Itoa(len(cc)-1) + " provided"
		} else {
			recv := ck.Get(cc[1])
			fmt.Printf("Key: %v, Val: %v\n", cc[1], recv)
		}

	default:
		err_msg = "command not found"
	}
	return err_msg
}
